# _*_ coding: utf-8 _*_
__author__ = 'yinlei'
__date__ = '2018-05-23 11:29'

import random
from string import digits, ascii_letters

from PIL import Image, ImageDraw, ImageFont


# Image :一个画布
# ImageDraw:一个画笔
# Imagefont 画笔的字体

class Captcha(object):
    # 生成几位数的验证码
    number = 4
    # 验证码图片的宽度和高度
    size = (150, 40)
    # 验证码的字体
    fontsize = 45
    # 加入干扰线的条数
    line_number = 5

    # 构建一个验证码的源码文本
    SOURCE = digits + ascii_letters

    # 生成验证码
    @classmethod
    def gene_graph_captcha(cls):
        # 验证码图片的宽度和高度
        width, height = cls.size
        # 创建图片
        image = Image.new('RGBA', (width, height), cls.__gene_random_color(0, 100))
        # 验证码字体
        font = ImageFont.truetype(cls.__gene_random_font(), cls.fontsize)
        # 创建画笔
        draw = ImageDraw.Draw(image)
        # 生成字符串
        text = cls.gene_text(cls.number)

        for i in range(cls.number):
            # 获取字体的尺寸
            font_width, font_height = font.getsize(text=text[i])
            draw.text((40 * i + 5, -10), text[i], font=font,
                      fill=cls.__gene_random_color(150, 255))

        # 绘制干扰线
        for x in range(0, cls.line_number):
            cls.__gene_line(draw, width, height)
        # 绘制噪点
        cls.__gene_points(draw, 10, width, height)
        with open('captcha.png', 'wb') as f:
            image.save(f)
        return (text, image)

    @classmethod
    def gene_text(cls, number=6):
        text_list = random.sample(cls.SOURCE, number)
        return ''.join(text_list)

    # 绘制干扰线
    @classmethod
    def __gene_line(cls, draw, width, height):
        begin = (random.randint(0, width), random.randint(0, height))
        end = (random.randint(0, width), random.randint(0, height))
        draw.line([begin, end], fill=cls.__gene_random_color(), width=2)

    @classmethod
    def __gene_points(cls, draw, point_change, width, height):
        chance = min(100, max(0, int(point_change)))  # 大小限制在[0,100]
        for w in range(width):
            for h in range(height):
                temp = random.randint(0, 100)
                if temp > 100 - chance:
                    draw.point((w, h), fill=cls.__gene_random_color())

    @classmethod
    def __gene_random_color(cls, start=0, end=255):
        return (random.randint(start, end), random.randint(start, end), random.randint(start, end))

    @classmethod
    def __gene_random_font(cls):
        font_list = [
            'angsa.ttf',
            'angsab.ttf',
            'angsai.ttf',
        ]
        font = random.choice(font_list)
        return 'utils/captcha/' + font
